package com.typhoon.spring_shiro.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.typhoon.spring_shiro.constants.CommonConstants;
import com.typhoon.spring_shiro.utils.Logs;

/**
 * 下载控制器
 * 
 * @author Ternence
 * @date 2016年7月22日
 */
@Controller
public class DownloadController {
    private static final Logger logger = Logs.get();
    /**
     * 从临时目录下载资源
     * 
     * 缓冲下载,节省服务器资源
     * 
     * @param fileName
     * @param response
     * @throws IOException
     * @date 2014年12月30日
     * @author Ternence
     */
    @RequestMapping(value = "download", method = RequestMethod.GET)
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response, HttpServletRequest request) throws IOException {
        logger.info("下载模板："+fileName);
        downloadFromPath(FilenameUtils.concat(CommonConstants.TEMP_RESOURCE_SERVER_PATH, fileName), response, request);
    }

    /**
     * 从永久目录下载资源
     * 
     * @param fileName
     * @param response
     * @throws IOException
     * @date 2015年4月8日
     * @author Ternence
     */
    @RequestMapping(value = "download2", method = RequestMethod.GET)
    public void download2(@RequestParam("fileName") String fileName, HttpServletResponse response, HttpServletRequest request) throws IOException {
        downloadFromPath(FilenameUtils.concat(CommonConstants.RESOURCE_SERVER_PATH, fileName), response, request);
    }

    private void downloadFromPath(String fileName, HttpServletResponse response, HttpServletRequest request) throws IOException {
        // TODO
        // 此处路径需要优化，目前各个下载模块生成的文件名称类似于“saofu-web1422072440110.xls”，文件名称和路径最后一截混在一块了。
        String rspName = fileName;
        File file = new File(rspName);
        if (!file.exists()) {
            // 如果文件不存在，不进行下载操作
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        int nLen = 0;
        byte buff[] = new byte[1024];
        OutputStream sos = null;
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(file);;
            response.setContentLength((int) file.length());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("name", file.getName());

            response.setHeader("Content-disposition", "attachment; filename*=utf-8'zh_cn'" + URLEncoder.encode(file.getName(), "UTF-8") + "");
            sos = response.getOutputStream();
            sos.flush();
            while ((nLen = fis.read(buff)) > 0) {
                sos.write(buff, 0, nLen);
            }
            sos.flush();
            sos.close();
        } catch (Exception e) {
            throw e;
        } finally {
        	IOUtils.closeQuietly(fis);
        }
    }
}
